package com.example.lotterybackend.common.utils;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;
import org.springframework.util.ReflectionUtils;

import java.util.List;
import java.util.concurrent.Callable;

/**
 * 自定义序列化工具
 * @author ricejson
 */
public class JacksonUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 序列化方法
     * @param obj 待序列化对象
     * @return 序列化字符串
     */
    public static String writeValueAsString(Object obj) {
        return tryParse(() -> {
            return objectMapper.writeValueAsString(obj);
        });
    }

    /**
     * 反序列化方法
     * @param content 原始内容
     * @param valueType 反序列化类型
     * @return
     * @param <T> 泛型参数
     */
    public static <T> T readValue(String content, Class<T> valueType) {
        return tryParse(() -> {
            return objectMapper.readValue(content, valueType);
        });
    }

    /**
     * 反序列化列表方法
     * @param content 原始内容
     * @param valueType 反序列化元素类型
     * @return
     * @param <T> 泛型参数
     */
    public static <T> List<T> readValueAsList(String content, Class<T> valueType) {
        return tryParse(() -> {
            JavaType javaType = objectMapper.getTypeFactory()
                    .constructParametricType(List.class, valueType);
            return objectMapper.readValue(content, javaType);
        });
    }

    private static final <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JsonParseException.class);
    }

    private static final <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception var4) {
            if (check.isAssignableFrom(var4.getClass())) {
                throw new JsonParseException(var4);
            } else {
                ReflectionUtils.rethrowRuntimeException(var4);
                throw new IllegalStateException(var4);
            }
        }
    }

}
